<template>
	<view class="home_wrap">
		<!-- 背景 -->
		<view class="bg3"></view>
		<view class="bg1"></view>
		<view class="bg2"></view>
		<!-- <image class="wallet_bg_img" src="./images/wallet.png" mode=""></image> -->

		<!-- 上方占位盒子 -->
		<view class="top_placeholder_box"></view>

		<!-- 头部 -->
		<view class="header_box">
			<view class="oper_box">
				<!-- 设置 -->
				<view class="oper_item_box" @click="settingClick">
					<image src="./images/kefu.svg" mode=""></image>
				</view>
			</view>
		</view>

		<!-- 	首页
		<button @click="toBusinessCard">跳转到名片展示页</button>
		<button @click="toCreateBusinessCard">跳转到创建名片页页</button> -->
		<view class="user_info_box" @click="loginClick">
			<view class="avatar_box">
				<view v-if="!userStore.isLogin" @click.stop="avatarClick">
					<wd-img :enable-preview="true" :width="58" :height="58" round :src="'https://d.lohand.com:1112/lohandMp/image/avatar_default.png'">
						<template #loading>
							<view class="loading-wrap">
								<wd-loading />
							</view>
						</template>
					</wd-img>
				</view>
				<view v-else @click.stop="avatarClick">
					<wd-img :enable-preview="true" :width="58" :height="58" round :src="avatarUrl">
						<template #loading>
							<view class="loading-wrap">
								<wd-loading />
							</view>
						</template>
					</wd-img>
				</view>
			</view>
			<!-- 已登录文本 -->
			<view class="text_box" v-if="userStore.isLogin">
				<view class="top">
					<text class="nick_name">{{ userNearName }}</text>
					<text class="position">{{ userStore.userInfo.cardUserPosition }}</text>
					<view class="home_location_box">
						<image class="label_icon_img" src="./images/place.svg" mode=""></image>
						<text class="home_location_value">{{ homeLocationInfo }}</text>
					</view>

					<view class="company_box">
						<image class="label_icon_img" src="./images/company.svg" mode=""></image>
						<text class="company_name">{{ userStore.userInfo.companyName ? userStore.userInfo.companyName : '未知公司' }}</text>
					</view>
				</view>
			</view>
			<!-- 未登录文本 -->
			<view class="sign_in_now_text" v-else>
				<text class="top_text">请使用您的手机号,登录/注册</text>
				<view class="bottom_box">
					<text class="text">点击登录</text>
				</view>
			</view>
		</view>

		<!-- 卡片操作 -->
		<!-- <view class="module_card_box">
			<wd-card title="功能栏">
				<image class="module_right_top_jb" src="./images/module_right_top_jb.svg" mode=""></image>
				<view class="module_box">
					<view class="module_item_box" v-for="(ml, indexM) in moduleList" :key="indexM">
						<view :class="`content_box ${ml.icon}`" @click="moduleClick(ml)">
							<ModuleIcon :icon="ml.icon"></ModuleIcon>
							<text class="module_title_text">{{ ml.title }}</text>
						</view>
					</view>
				</view>
			</wd-card>
		</view> -->
		<!-- <view class="action_box">
			<view class="action_item_box">
				
			</view>
		</view> -->
		<!-- 操作卡片栏 -->
		<view class="operation_card_box">
			<view class="operation_item_box" v-for="(ml, indexM) in moduleList" :key="indexM" @click="moduleClick(ml)">
				<ModuleIcon :icon="iconDisposeFunc(ml.icon)" :data="ml"></ModuleIcon>
			</view>
		</view>
		<TechnicalSupport></TechnicalSupport>
	</view>
</template>

<script>
import { defineComponent, ref, onMounted, onUnmounted } from 'vue'

export default defineComponent({
	name: 'Index'
})
import './index.scss'
</script>
<script setup>
import { onShareAppMessage, onLoad } from '@dcloudio/uni-app'
import { useUserStore } from '@/stores/user.js'
import ModuleIcon from './components/moduleIcon.vue'
import TechnicalSupport from '@/components/technicalSupport.vue'
import { getOpenIdApi, selectUserInfoApi } from '@/api/user.js'
import { selectCardUserApi } from '@/api/personal.js'

const userStore = useUserStore()

// 头像链接
const avatarUrl = ref('')

// 昵称
const userNearName = ref('')
// 当前 provider
// const currentProvider = ref("")

// 头像点击事件
const avatarClick = () => {
	console.log('1111', 1111)
}

// 设置点击事件
const settingClick = () => {
	// console.log('设置');
	uni.showToast({
		title: '暂未开放',
		icon: 'none',
		mask: true,
		duration: 1000
	})
}

// icon处理函数
const iconDisposeFunc = (icon) => {
	let nIcon = ''
	if (icon == 'create-business-card') {
		if (userStore.isCreateBusinessCard) {
			nIcon = 'edit-business-card'
		} else {
			nIcon = 'create-business-card'
		}
	} else {
		nIcon = icon
	}
	return nIcon
}

// 模块列表
const moduleList = ref([
	{
		title: '我的名片',
		icon: 'my-business-card',
		path: '/pages/businessCard/businessCard',
		name: 'myBusinessCard'
	},
	{
		title: '创建名片',
		icon: `create-business-card`,
		path: '/pages/createBusinessCard/createBusinessCard',
		name: 'createBusinessCard'
	},
	{
		title: '名片夹',
		icon: 'business-card-holder',
		path: '/pages/businessCardHolder/businessCardHolder',
		name: 'businessCardHolder'
	},
	{
		title: '使用手册',
		icon: 'service-manual',
		path: '/pages/serviceManual/serviceManual',
		name: 'serviceManual'
	}
])

// 模块点击事件
const moduleClick = (ml) => {
	console.log('点击模块', ml)
	// console.log('是否登录',是否登录);
	// 先判断是否登录，如果已经登录则执行跳转，如果没有登录则弹窗提示登录
	if (!userStore.isLogin) {
		uni.showToast({
			title: '请先登录',
			mask: true,
			duration: 1000,
			icon: 'error'
		})
		return
	}

	console.log('path', ml.path)
	// console.log('去使用手册')

	let tPath = ml.path
	switch (ml.name) {
		case 'myBusinessCard':
			if (userStore.isCreateBusinessCard) {
				tPath = tPath + `?beDisplayedUserId=${userStore.userInfo.userId}&beDisplayedUserName=${userStore.userInfo.cardUserName}`
			} else {
				uni.showToast({
					title: '您未创建名片',
					icon: 'none',
					mask: true,
					duration: 1000
				})
				return
			}
			uni.navigateTo({
				url: tPath
			})
			break

		case 'createBusinessCard':
			uni.navigateTo({
				url: tPath
			})
			break

		case 'businessCardHolder':
			uni.navigateTo({
				url: tPath
			})
			break
		case 'serviceManual':
			uni.showToast({
				title: '暂未开放',
				icon: 'none',
				mask: true,
				duration: 1000
			})
			// console.log('使用手册')
			// uni.navigateTo({
			// 	url:tPath
			// })
			break

		default:
			break
	}
}

// 免登码
const loginCode = ref('')

// 登录点击事件
const loginClick = () => {
	// 判断是否登录
	if (!userStore.isLogin) {
		console.log('去登录')
		uni.navigateTo({
			url: '/pages/register/register'
		})
	}
}

// 归属地信息
const homeLocationInfo = ref('')

// 获取归属地
const getHomeLocation = () => {
	console.log('获取')
	uni.getLocation({
		type: 'gcj02',
		success: (res) => {
			console.log(res)
			let key = '28ab7a162ee8eda5c34858280f9863f4'
			let address = ''
			let lat = res.latitude
			let lng = res.longitude
			uni.request({
				url: `https://restapi.amap.com/v3/geocode/regeo?output=json&location=${res.longitude},${res.latitude}&key=${key}&radius=1000&extensions=all`,
				success: (res) => {
					console.log('高德地图API接口返回信息', res)
					let province = res.data.regeocode.addressComponent.province
					let city = res.data.regeocode.addressComponent.city
					homeLocationInfo.value = `${province} ${city}`
				},
				fail: (error) => {
					homeLocationInfo.value = '未知'
				}
			})
		},
		fail: (err) => {
			console.log(err)
		}
	})
}

onShareAppMessage(() => {
	return {
		title: '陆恒电子名片☺',
		path: '/pages/index/index'
	}
})

const toBusinessCard = () => {
	uni.navigateTo({
		url: '/pages/businessCard/businessCard?userId=111'
	})
}

const toCreateBusinessCard = () => {
	uni.navigateTo({
		url: '/pages/createBusinessCard/createBusinessCard?userId=111'
	})
}

// 获取免登码
const getLoginCode = () => {
	uni.showLoading({
		title: '登录中',
		mask: true
	})
	uni.login({
		provider: 'weixin', //使用微信登录
		onlyAuthorize: true,
		success: function (res) {
			console.log('loginRes', res)
			console.log('成功拿到免登码!')
			userStore.loginCode = res.code
			console.log('code', userStore.loginCode)
			getOpenIdByCodeFunc()
			// getSessionKeyFunc()
		}
	})
}

// 获取session_key
const getSessionKeyFunc = () => {
	uni.request({
		url: 'https://api.weixin.qq.com/sns/jscode2session', // 请求微信服务器
		method: 'GET',
		data: {
			appid: 'wxa83a95ff5502b74f', //你的小程序的APPID
			secret: '107afdf1420d1dc15622b9747c18e263', //你的小程序秘钥secret,
			js_code: userStore.loginCode, //uni.login 登录成功后的code
			grant_type: 'authorization_code' //此处为固定值
		},
	}).then((res)=>{
		uni.showToast({
			title:"获取session_成功",
			icon:"none",
			mask:true,
			duration:2000
		})
		console.log('getSession',res);
		userStore.sessionKey = res.data.session_key
		userStore.currentOpenId = res.data.openid
		selectUserInfoFunc()
	}).catch((err)=>{
		uni.showToast({
			title:'失败',
			icon:"none",
			mask:true,
			duration:2000
		})
	})
}

// 通过code获取OpenId的函数
const getOpenIdByCodeFunc = async () => {
	console.log('11', 11)
	await getOpenIdApi(userStore.loginCode)
		.then((res) => {
			console.log('获取openid',res);
				userStore.sessionKey = res.data.data.sessionKey
			userStore.currentOpenId = res.data.data.openId
			console.log('openOId', userStore.currentOpenId)
			selectUserInfoFunc()
		})
		.catch((err) => {
			console.log('err', err)
		})
}

// 查询用户信息的函数
const selectUserInfoFunc = async () => {
	
	let errOpenId = 'ofAV57WCXVajfgSttELOb82_8wTT'
	// userStore.currentOpenId
	await selectUserInfoApi(userStore.currentOpenId)
		.then((res) => {
			// 判断是否存在用户
			if (res.data.result == 'error') {
				console.log('查询用户信息err', res)
				// uni.navigateTo({
				// 	url:"/pages/login/login"
				// })
				uni.hideLoading()
			} else if (res.data.result == 'success') {
				console.log('查询用户信息res', res)
				userStore.userInfo.userId = res.data.data.userId
				avatarUrl.value = res.data.data.userProfilePicture
				userNearName.value = res.data.data.userNearName
				console.log('userId', userStore.userInfo.userId)
				userStore.isLogin = true
				uni.hideLoading()
				selectCardUserFunc()
			}
		})
		.catch((err) => {
			console.log('查询用户信息', err)
		})
}

// 查询个人资料的函数
const selectCardUserFunc = async () => {
	await selectCardUserApi(userStore.userInfo.userId).then((res) => {
		console.log('查询个人资料res', res)
		// 判断data是否为空
		if (res.data.data == null) {
			// 该用户未创建名片
			userStore.isCreateBusinessCard = false
		} else {
			// 该用户已创建名片
			userStore.isCreateBusinessCard = true
			userStore.userInfo = res.data.data
			console.log('userInfo', userStore.userInfo)
		}
		// moduleList.value.forEach((module)=>{
		// 	if(module.name == 'createBusinessCard'){
		// 		module.title =  userStore.isCreateBusinessCard ? '编辑名片' : '创建名片'
		// 		module.icon = `${userStore.isCreateBusinessCard ? 'edit' : 'create'}-business-card`
		// 	}
		// })
		getHomeLocation()
		console.log('isCreateBusinessCard', userStore.isCreateBusinessCard)
	})
}

let getHomeLocationInter = null 

onMounted(() => {
	getLoginCode()
	// getHomeLocationInter = setInterval(()=>{
	// 	if(userStore.isLogin){
	// 			getHomeLocation()
	// 			clearInterval(getHomeLocationInter)
	// 			getHomeLocationInter = null
	// 	}
	// },1000)

	// getProvider()
})


onUnmounted(()=>{
	// clearInterval(getHomeLocationInter)
	// getHomeLocationInter = null
})
</script>

<style lang="scss" scoped>
:deep(.loading-wrap) {
	width: 100%;
	height: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
}
</style>
